package com.chookss.mine.personal;


import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;

import com.chookss.tools.SignUtils2;
import com.google.gson.reflect.TypeToken;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.home.entity.NewsEntiry;
import com.chookss.mine.adapter.MyNewsListsAdapter;
import com.chookss.tools.MyToast;
import com.chookss.tools.old.SignUtils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.tools.MyEvent;
import com.chookss.tools.Utils;
import com.chookss.view.consecutivescroller.ConsecutiveScrollerLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

// 新闻集合列表
@SuppressLint("ValidFragment")
public class MyNewsFragment extends Fragment implements OnRefreshListener, OnLoadMoreListener {
    public MyNewsFragment() {

    }

    public Context mContext;
    Unbinder unbinder;
    @BindView(R.id.srlView)
    ConsecutiveScrollerLayout srlView;
    @BindView(R.id.rvView)
    RecyclerView rv;
    @BindView(R.id.llNone)
    LinearLayout llNone;
    @BindView(R.id.ivNone)
    ImageView ivNone;
    @BindView(R.id.tvNone)
    TextView tvNone;
    @BindView(R.id.tvNone2)
    TextView tvNone2;
    private String employeeCode;
    private MyNewsListsAdapter adapter;
    private List<NewsEntiry> list = new ArrayList<>();
    private int currentPage = 1;
    private String pageSize = "10";
    private boolean isEnd = false;//是否到底
    private RelativeLayout.LayoutParams params;
    private int type = 1;//0自己的主页1别人的主页

    public MyNewsFragment(String employeeCode, int type) {
        this.employeeCode = employeeCode;
        this.type = type;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_my_video, container, false);
        unbinder = ButterKnife.bind(this, view);
        init();
        //注册接受
        EventBus.getDefault().register(this);
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }


    private void init() {
//        params = (RelativeLayout.LayoutParams) srlView.getLayoutParams();
//        params.setMargins(0, Utils.dip2px(mContext, 10), 0, 0);
//        srlView.setLayoutParams(params);
        srlView.setPadding(0, Utils.dip2px(mContext, 12), 0, 0);
        ivNone.setBackgroundResource(R.drawable.icon_default_no_common);
        tvNone.setText("新闻集还是空的");
        tvNone2.setText("快去发布你的第一条新闻吧");
        rv.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager
                .VERTICAL, false));
        rv.setPadding(Utils.dip2px(mContext,12),0,Utils.dip2px(mContext,12),0);
        adapter = new MyNewsListsAdapter(R.layout.item_personal_news,mContext,list);
        rv.setAdapter(adapter);
        ((SimpleItemAnimator) rv.getItemAnimator()).setSupportsChangeAnimations(false);
        getData();
    }

    private RefreshLayout refreshLayout;

    @Override
    public void onRefresh(@androidx.annotation.NonNull final RefreshLayout refreshLayout) {
        this.refreshLayout = refreshLayout;
        isEnd = false;
        currentPage = 1;
        getData();
    }

    @Override
    public void onLoadMore(@androidx.annotation.NonNull final RefreshLayout refreshLayout) {
        this.refreshLayout = refreshLayout;
        if (isEnd) {//has next page
            MyToast.show("没有更多数据了");
            loadEnd();
        } else {
            currentPage++;
            getData();
        }
    }

    private void getData() {

        Map<String, String> allmap = new HashMap<>();
        allmap.put("employeeCode", employeeCode);
        allmap.put("pageNum", currentPage + "");
        allmap.put("pageSize", pageSize);
        MyHttpRequest.getDefault().postRequest(new TypeToken<LzyResponse<List<NewsEntiry>>>() {
        }.getType(), null, Urls.getMyNews, SignUtils2.makeSignStr(allmap), false, new ObserverCallback<List<NewsEntiry>>() {
            @Override
            public void onSuccess(List<NewsEntiry> data) {
                if (currentPage == 1) {
                    list.clear();
                    adapter.notifyDataSetChanged();
                }
                if(rv==null||llNone==null){
                    return;
                }
                int oldIndex=list.size();
                if (data != null && data.size() > 0) {
                    list.addAll(data);
                    adapter.notifyItemRangeChanged(oldIndex,data.size());
                    rv.setVisibility(View.VISIBLE);
                    llNone.setVisibility(View.GONE);
                } else {
                    isEnd = true;
                    if (list.size() == 0) {
                        rv.setVisibility(View.GONE);
                        llNone.setVisibility(View.VISIBLE);
                    }
                }
                loadEnd();
            }

            @Override
            public void onError(String errorMsg) {
                loadEnd();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void loadEnd() {
        if (null != refreshLayout && refreshLayout.getState() == RefreshState.Loading)
            refreshLayout.finishLoadMore(true);
        if (null != refreshLayout && refreshLayout.getState() == RefreshState.Refreshing)
            refreshLayout.finishRefresh(true);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getHashMap() != null) {
            Map<String, String> map = messageEvent.getHashMap();

        } else {
            String msg = messageEvent.getMessage();
            if (Utils.isNull(msg)) {
                return;
            }
            if ("RefreshNews".equals(msg)) {
                currentPage = 1;
                isEnd = false;
                getData();
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        unbinder.unbind();
    }

}
